package com.ciwong.epaper.modules.pad.contentprovider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class TokenContentProvider extends ContentProvider {

	
	private static final String DB_NAME  ="epaperhdtoken.db";
    public static final String DB_TABLE ="tokeninfo";

    //版本号升级，用于字段增删
    private static final int DB_VERSION = 4;

    private SQLiteDatabase db;
    private DBOpenHelper   dbOpenHelper;

    private static final int MULTIPLE_TOKEN = 1;
    private static final int SINGLE_TOKEN = 2;
    private static final UriMatcher uriMatcher ;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(LoginToken.AUTHORITY, LoginToken.PATH_MULTIPLE, MULTIPLE_TOKEN);
        uriMatcher.addURI(LoginToken.AUTHORITY, LoginToken.PATH_SINGLE, SINGLE_TOKEN);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        db = dbOpenHelper.getWritableDatabase();
        if(db == null){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(DB_TABLE);
        switch (uriMatcher.match(uri)){
            case SINGLE_TOKEN:
                qb.appendWhere(LoginToken.KEY_ID+"="+uri.getPathSegments().get(1));
                break;
            default:
                break;
        }
        try {
            Cursor cursor = qb.query(db,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
            return cursor;
        }catch (Exception e){

        }

        return null;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
            case MULTIPLE_TOKEN:
                return LoginToken.MIME_TYPE_MULTIPLE;
            case SINGLE_TOKEN:
                return LoginToken.MIME_TYPE_SINGLE;
            default:
                throw new IllegalArgumentException("Unkown uro:"+uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        try {
            long id =db.insert(DB_TABLE, null, values);
            if(id>0){
                Uri newUri = ContentUris.withAppendedId(LoginToken.CONTENT_URI,id);
                getContext().getContentResolver().notifyChange(newUri, null);
                return newUri;
            }
        }catch (Exception e){

        }
        return  uri;

    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        try {
            switch (uriMatcher.match(uri)){
                case MULTIPLE_TOKEN:
                    count = db.delete(DB_TABLE, selection, selectionArgs);
                    break;
                case SINGLE_TOKEN:
                    String segment = uri.getPathSegments().get(1);
                    count = db.delete(DB_TABLE, LoginToken.KEY_ID + "=" + segment, selectionArgs);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported URI:" + uri);
            }
            getContext().getContentResolver().notifyChange(uri,null);
        }catch (Exception e){

        }

        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int count;
        switch (uriMatcher.match(uri)){
            case MULTIPLE_TOKEN:
                count = db.update(DB_TABLE, values, selection, selectionArgs);
                break;
            case SINGLE_TOKEN:
                String segment = uri.getPathSegments().get(1);
                count = db.update(DB_TABLE, values, LoginToken.KEY_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknow URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    private static class DBOpenHelper extends SQLiteOpenHelper {

        private static final String DB_CREATE = "create table "+
                DB_TABLE+"("+LoginToken.KEY_ID+" integer primary key autoincrement, "+
                LoginToken.KEY_REFTOKEN+" text not null, "
                + LoginToken.KEY_TOKEN+" text not null, "
                + LoginToken.KEY_USER_ID+" text not null, "
                + LoginToken.KEY_AVATAR+" text, "
                + LoginToken.KEY_REAL_NAME+" text, "
                + LoginToken.KEY_NICK_NAME+" text, "
                + LoginToken.KEY_MOBILE+" text, "
                + LoginToken.KEY_USER_ROLE+" text, "
                +LoginToken.KEY_EXPIRESIN+" text not null,"

                +LoginToken.KEY_SCHOOL_ID+" text ,"
                +LoginToken.KEY_SCHOOL_NAME+" text ,"
                +LoginToken.KEY_SCHOOL_AREA+" text ,"
                +LoginToken.KEY_SCHOOL_AREA_NAME+" text ,"
                +LoginToken.KEY_CLASS_ID+" text ,"
                 +LoginToken.KEY_CLASS_NAME+" text )";


        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(db);

        }
    }
}
